<template>
  <div class="site-wrapper">
    <div class="header clearfix">
      <el-button size="small" type="primary" :disabled="isObserver" @click="createTask">新增</el-button>
      <el-button size="small" type="primary" :disabled="multipleSelection.length === 0 || isObserver" @click="delTask(false)">批量删除</el-button>
      <div class="filter" @click="showFilter = true;"><img src="../../../../assets/livolobim/filter.png" alt="">搜索</div>
      <div class="mask" v-if="showFilter" @click="showFilter = false;"></div>
      <div class="filter-wrapper" v-if="showFilter">
        <span class="filter-arrow"></span>
        <span class="filter-white"></span>
        <div class="filter-header">搜索</div>
        <el-form :model="filterData" style="padding: 0 16px;" label-width="90px">
          <el-form-item label="优先级">
            <el-select v-model="filterData.priority" style="width: 100%;"  placeholder="请选择">
              <el-option v-for="item in priorityArr" :key="item.id" :label="item.name" :value="item.id"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="任务类型">
            <el-select v-model="filterData.taskType" style="width: 100%;"  placeholder="请选择">
              <el-option v-for="item in rwlx" :key="item.id" :label="item.name" :value="item.id"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="执行人">
            <div class="select-btn" v-if="filterPeople.assigneeId">
              <span>{{filterPeople.assigneeName}}</span>
              <div class="del" v-if="!isCheck" @click="delMember(filterPeople)">移除</div>
            </div>
            <div v-if="!filterPeople.assigneeId" @click="selectDingUsers(filterPeople)" class="select-btn">请选择</div>
          </el-form-item>
          <el-form-item label="客户">
            <el-select
              style="width: 100%;"
              v-model="filterData.customerId"
              filterable
              remote
              reserve-keyword
              @change="changeCustomer"
              placeholder="请输入客户名称、编号(最少输入2个字母)"
              :remote-method="remoteMethod"
              :loading="loading">
              <el-option
                v-for="item in custormerList"
                :key="item.id"
                :label="item.name"
                :value="item.id">
              </el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="处理情况">
            <el-select v-model="filterData.processed" style="width: 100%;"  placeholder="请选择">
              <el-option v-for="item in handleArr" :key="item.id" :label="item.name" :value="item.id"></el-option>
            </el-select>
          </el-form-item>
        </el-form>
        <div slot="footer" class="dialog-footer">
          <el-button style="float:right;margin-right: 16px;" size="small" type="primary" @click="searchItem(true)">确定</el-button>
          <el-button style="float:right;margin-right: 16px;" size="small" @click="resetFilter">重置</el-button>
        </div>
      </div>
    </div>
    <div class="data-wrapper">
      <el-table :height="tableHeight" :data="tableData" border style="width: 100%" @sort-change="sortList" @selection-change="handleSelectionChange">
        <el-table-column align="center" type="selection" width="55"></el-table-column>
        <el-table-column align="center" prop="content" label="任务内容" min-width="150"></el-table-column>
        <el-table-column align="center" prop="assigneeName" label="执行人" min-width="100"></el-table-column>
        <el-table-column align="center" prop="taskTypeMean" label="任务类型" min-width="120"></el-table-column>
        <el-table-column align="center" prop="taskStatusMean" label="任务状态" min-width="100"></el-table-column>
        <el-table-column sortable="action_time" align="center" prop="actionTime" label="执行时间" min-width="100"></el-table-column>
        <el-table-column align="center" prop="actionTypeMean" label="任务方式" min-width="100"></el-table-column>
        <el-table-column sortable="priority" align="center" prop="priorityMean" label="优先级" min-width="70"></el-table-column>
        <el-table-column label="操作" min-width="180" align="center">
          <template slot-scope="scope">
            <el-button @click="openEdit(scope.row, true)" type="text" size="small">查看</el-button>
            <el-button v-if="scope.row.taskStatus === 0 && !isObserver" @click="openEdit(scope.row, false)" type="text" size="small">编辑</el-button>
            <el-button v-if="scope.row.taskStatus === 0 && !isObserver" @click="openHandle(scope.row)" type="text" size="small">处理</el-button>
            <el-button v-if="!isObserver" @click="delTask(scope.row.id)" type="text" size="small">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
      <el-pagination
        style=""
        @size-change="sizeChangeHandle"
        @current-change="currentChangeHandle"
        :current-page="page"
        :page-sizes="[15, 20, 50, 100]"
        :page-size="pageSize"
        :total="totalPage"
        layout="total, sizes, prev, pager, next, jumper">
      </el-pagination>
      <el-dialog width="1000px" :visible.sync="showForm" :show-close="true">
        <div slot="title">
          <h2 style="text-align:center;margin-bottom:0;">{{form.id? isCheck? isHandle ? '处理':'查看': '编辑': '创建'}}待办事项</h2>
        </div>
        <div class="form-wrapper" style="padding: 0 20px;">
          <el-form ref="form" :model="form" label-width="100px">
            <el-row :gutter="20">
              <el-col :span="12">
                <el-form-item style="font-weight: bold;" label="任务类型：">
                  <span slot="label">任务类型<span style="color: red;">*</span>：</span>
                  <el-select :disabled="isCheck" style="width: 100%;" v-model="form.taskType" placeholder="请选择任务类型">
                    <el-option v-for="item in rwlx" :key="item.id" :label="item.name" :value="item.id"></el-option>
                  </el-select>
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item style="font-weight: bold;" label="任务方式：">
                  <span slot="label">任务方式<span style="color: red;">*</span>：</span>
                  <el-radio :disabled="isCheck" style="margin-right: 10px;" v-model="form.actionType" :label="1">单次任务</el-radio>
                  <el-radio :disabled="isCheck" style="margin-right: 10px;" v-model="form.actionType" :label="2">重复任务</el-radio>
                  <el-radio :disabled="isCheck" style="margin-right: 10px;" v-model="form.actionType" :label="3">限期完成</el-radio>
                </el-form-item>
              </el-col>
            </el-row>
            <el-row :gutter="20">
              <el-col :span="12">
                <el-form-item style="font-weight: bold;" label="客户：">
                  <el-select
                    style="width: 100%;"
                    v-model="form.customerId"
                    filterable
                    remote
                    :disabled="isCheck"
                    reserve-keyword
                    placeholder="请输入客户名称、编号(最少输入2个字母)"
                    :remote-method="remoteMethod"
                    :loading="loading">
                    <el-option
                      v-for="item in custormerList"
                      :key="item.id"
                      :label="item.name"
                      :value="item.id">
                    </el-option>
                  </el-select>
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item style="font-weight: bold;" label="执行时间：">
                  <el-date-picker :disabled="isCheck" type="date" value-format="yyyy-MM-dd" placeholder="选择日期" v-model="form.actionTime" style="width: 100%;"></el-date-picker>
                </el-form-item>
              </el-col>
            </el-row>
            <el-row :gutter="20">
              <el-col :span="24">
                <el-form-item style="font-weight: bold;" label="任务内容：">
                  <span slot="label">任务内容<span style="color: red;">*</span>：</span>
                  <el-input type="textarea" :disabled="isCheck" :rows="3" placeholder="请输入任务内容" v-model="form.content"></el-input>
                </el-form-item>
              </el-col>
            </el-row>
            <el-row :gutter="20">
              <el-col :span="24">
                <el-form-item style="font-weight: bold;" label="执行人：">
                  <span slot="label">执行人<span style="color: red;">*</span>：</span>
                  <div class="select-btn" v-if="form.assigneeId">
                    <span>{{form.assigneeName}}</span>
                    <div class="del" v-if="!isCheck" @click="delMember(form)">移除</div>
                  </div>
                  <div v-if="!form.assigneeId && !isCheck" @click="selectDingUsers(form)" class="select-btn">请选择</div>
                </el-form-item>
              </el-col>
            </el-row>
            <el-row :gutter="20">
              <el-col :span="12">
                <el-form-item style="font-weight: bold;" label="优先级：">
                  <span slot="label">优先级<span style="color: red;">*</span>：</span>
                  <el-select :disabled="isCheck" style="width: 100%;" v-model="form.priority" placeholder="请选择优先级">
                    <el-option v-for="item in priorityArr" :key="item.id" :label="item.name" :value="item.id"></el-option>
                  </el-select>
                </el-form-item>
              </el-col>
            </el-row>
            <el-row :gutter="20">
              <el-col :span="24">
                <el-form-item style="font-weight: bold;" label="附件：">
                  <input ref="uploadInput" style="display:none;" type="file" @change="uploadFile($event)" multiple>
                  <span class="addfilebtn" v-if="!isCheck" @click="$refs.uploadInput.click()"><i class="el-icon-paperclip" style=""></i>添加附件</span>
                  <div class="fileitem" v-for="(file, idx) in form.attachments" :key="idx">
                    <img style="width:16px;height:16px;position:relative;top:-2px;margin-right:2px;" :src="getPic(file.name)" alt="">
                    <span @click="downloadFile(file.url, file.name)" style="width: 60%;overflow:hidden;text-overflow: ellipsis;vertical-align:bottom;white-space:nowrap;display:inline-block;">{{file.name}}</span>
                    <span class="uploadtip" v-if="file.url && !isCheck" @click.stop="delFile(idx)"><i class="el-icon-delete"></i></span>
                    <span class="uploadtip" style="color: red;cursor:none;" v-if="!file.url">上传中<i class="el-icon-loading"></i></span>
                  </div>
                </el-form-item>
              </el-col>
            </el-row>
            <el-row v-if="form.taskStatus === 1 || form.taskStatus === -1" :gutter="20">
              <el-col :span="12">
                <el-form-item style="font-weight: bold;" label="处理状态：">
                  {{form.taskStatus === 1 ? '完成': '中止'}}
                </el-form-item>
              </el-col>
            </el-row>
            <el-row v-if="form.taskStatus === 1 || form.taskStatus === -1" :gutter="20">
              <el-col :span="24">
                <el-form-item style="font-weight: bold;" label="处理说明：">
                  <el-input type="textarea" disabled :rows="3" v-model="form.taskResult"></el-input>
                </el-form-item>
              </el-col>
            </el-row>
            <el-row v-if="isHandle" :gutter="20">
              <el-col :span="12">
                <el-form-item style="font-weight: bold;" label="处理状态：">
                  <el-radio style="margin-right: 10px;" v-model="handleForm.taskStatus" :label="1">完成</el-radio>
                  <el-radio style="margin-right: 10px;" v-model="handleForm.taskStatus" :label="-1">中止</el-radio>
                </el-form-item>
              </el-col>
            </el-row>
            <el-row v-if="isHandle" :gutter="20">
              <el-col :span="24">
                <el-form-item style="font-weight: bold;" label="处理说明：">
                  <el-input type="textarea" :rows="3" placeholder="请输入处理说明" v-model="handleForm.taskResult"></el-input>
                </el-form-item>
              </el-col>
            </el-row>
            <el-form-item>
              <el-button style="float:right;" size="small" @click="showForm = false">关闭</el-button>
              <el-button v-if="!isCheck" style="float:right;margin-right: 10px;" size="small" type="primary" @click="saveForm">保存</el-button>
              <el-button v-if="isHandle" style="float:right;margin-right: 10px;" size="small" type="primary" @click="dealWithTask">保存</el-button>
            </el-form-item>
          </el-form>
        </div>
      </el-dialog>
    </div>
  </div>
</template>

<script>
import dingMixin from "@/mixins/ding";
import formUtil from "@/utils/formUtil";
import {dateUtil} from '@/utils/dateUtil'

export default {
  data() {
    return {
      showFilter: false,
      loading:false,
      showForm: false,
      tableHeight: window.tableHeight,
      tableData: [],
      page:1,
      pageSize: 15,
      totalPage: 1,
      handleForm: {
        id: '',
        taskStatus: '',
        taskResult: ''
      },
      priorityArr: [{
        name: '低',
        id: 1
      },{
        name: '中',
        id: 2
      },{
        name: '高',
        id: 3
      }],
      handleArr: [{
        name: '已处理',
        id: true
      },{
        name: '未处理',
        id: false
      }],
      form: {
        customerId: '',
        taskType: '',
        customerNo: '',
        customerName: '',
        actionType: '',
        actionTime: '',
        priority: '',
        content: '',
        assigneeId: '',
        assigneeName: '',
        attachments: [],
        taskStatus: ''
      },
      formVerify: {
        taskType: '请选择任务类型',
        actionType: '请选择任务方式',
        priority: '请选择优先级',
        content: '请输入内容',
        assigneeId: '请选择执行人'
      },
      custormerList: [],
      filterData: {
        priority: '',
        taskType: '',
        assigneeId: '',
        customerNo: '',
        processed: '',
        customerId: ''
      },
      filterPeople:{
        assigneeId: '',
        assigneeName: '',
      },
      rwlx: [],
      multipleSelection: [],
      isCheck: false,
      isHandle: false,
      asc: '',
      sortFile: ''
    }
  },
  mixins: [dingMixin],
  async mounted() {
    this.$nextTick(() => {
      this.tableHeight = document.documentElement['clientHeight'] - 170;
    })
    window.onresize = () => {
      this.tableHeight = document.documentElement['clientHeight'] - 170
    }
    this.rwlx = await this.$httpN.postQ('crm/dict/list', {pid: '1290126082766385153'})
    this.searchItem(true);
  },
  computed: {
    isObserver() {
      return this.userInfo.roleIdList && this.userInfo.roleIdList.includes('1289086254290432001')
    }
  },
  methods: {
    sortList(sort) {
      console.log(sort)
      this.sortFile = sort.order? sort.prop === 'priorityMean'? 'priority': 'action_time': '';
      this.asc = sort.order === 'ascending'? true: sort.order === 'descending'? false : '';
      this.searchItem(true);
    },
    resetFilter() {
      this.filterData = {
        priority: '',
        taskType: '',
        assigneeId: '',
        customerNo: '',
        customerId: '',
        processed: ''
      };
      formUtil.resetData(this.filterPeople);
    },
    changeCustomer(val) {
      this.custormerList.forEach((item) => {
        if(item.id === val) {
          this.filterData.customerNo = item.code;
        };
      })
    },
    openHandle(target) {
      let newForm = formUtil.deepCopy(target);
      newForm.attachments = newForm.attachments ?JSON.parse(newForm.attachments): [];
      this.form = newForm;
      if(this.form.customerName) this.custormerList = [{name: this.form.customerName, id: this.form.customerId, code: this.form.customerNo}];
      this.showForm = true;
      this.isCheck = true;
      this.isHandle = true;
      formUtil.resetData(this.handleForm);
      this.handleForm.id = target.id;
      this.handleForm.taskStatus = 1;
    },
    async dealWithTask() {
      if(!await this.$httpN.postQ('crm/tdl/process', this.handleForm)) return;
      formUtil.submitSuccess('成功');
      this.showForm = false;
      this.searchItem(true);
    },
    handleSelectionChange(val) {
      this.multipleSelection = val;
    },
    delTask(id) {
      let ids = id ? [id]: this.multipleSelection.map(item => item.id);
      formUtil.submitConfirm('您确定要删除任务吗？', async ()=> {
        if(!await this.$httpN.postB('crm/tdl/delete', ids, false)) return;
        formUtil.submitSuccess('删除成功');
        this.searchItem(true);
      })
    },
    downloadFile: function (url, fileName) {//跨域文件路径、下载到本地的文件名
      if(/\.(bmp|gif|jpg|pic|png|tif|jpeg)$/.test(url)) return this.dingPreviewPic(url);
      if(!url) return;
      var x = new XMLHttpRequest();
      x.open("GET", url, true);
      x.responseType = 'blob';
      x.onload=function(e) {
        var url = window.URL.createObjectURL(x.response)
        var a = document.createElement('a');
        a.href = url
        a.download = fileName;
        a.click()
      }
      x.send();
    },
    getPic(filename) {
      if(filename) {
        if(/\.(bmp|gif|jpg|pic|png|tif|jpeg)$/.test(filename)){
          return 'https://livolo-office.oss-cn-hangzhou.aliyuncs.com/1276438103037435905.png'
        }else if(/\.(txt)$/.test(filename)){
          return 'https://livolo-office.oss-cn-hangzhou.aliyuncs.com/1276438530785140737.png'
        }else if(/\.(xls|xlsx)$/.test(filename)){
          return 'https://livolo-office.oss-cn-hangzhou.aliyuncs.com/1276438725690253314.png'
        }else if(/\.(doc|docx)$/.test(filename)){
          return 'https://livolo-office.oss-cn-hangzhou.aliyuncs.com/1276439195636850689.png'
        }else if(/\.(psd)$/.test(filename)){
          return 'https://livolo-office.oss-cn-hangzhou.aliyuncs.com/1276439984203751426.png'
        }else if(/\.(pdf)$/.test(filename)){
          return 'https://livolo-office.oss-cn-hangzhou.aliyuncs.com/1276440139145535490.png'
        }else if(/\.(ppt|pptx|dps|dpt)$/.test(filename)){
          return 'https://livolo-office.oss-cn-hangzhou.aliyuncs.com/1276440657859305473.png'
        }else if(/\.(rar|zip|arj|gz)$/.test(filename)){
          return 'https://livolo-office.oss-cn-hangzhou.aliyuncs.com/1276442063039193090.png'
        }else if(/\.(html|htm)$/.test(filename)){
          return 'https://livolo-office.oss-cn-hangzhou.aliyuncs.com/1276442135319633921.png'
        }else if(/\.(dwg|bak|dwt)$/.test(filename)){
          return 'https://livolo-office.oss-cn-hangzhou.aliyuncs.com/1276441741667459074.png'
        }else if(/\.(wav|aif|au|mp3|ram|wma|mmf)$/.test(filename)){
          return 'https://livolo-office.oss-cn-hangzhou.aliyuncs.com/1276442006684524546.png'
        }else if(/\.(avi|mov|rmvb|rm|flv|mp4)$/.test(filename)){
          return 'https://livolo-office.oss-cn-hangzhou.aliyuncs.com/1276442233483124737.png'
        }else{
          return 'https://livolo-office.oss-cn-hangzhou.aliyuncs.com/1276436590181343234.png'
        }
      }else {
        return 'https://livolo-office.oss-cn-hangzhou.aliyuncs.com/1276436590181343234.png'
      }
    },
    createTask() {
      this.showForm = true;
      this.isCheck = false;
      formUtil.resetData(this.form);
      this.form.priority = 1;
      this.form.taskStatus = 0;
      this.form.assigneeId = this.userInfo.dingId;
      this.form.assigneeName = this.userInfo.realName;
      this.isHandle = false;
    },
    async openEdit(target, isCheck) {
      let newForm = formUtil.deepCopy(target);
      newForm.attachments = newForm.attachments ?JSON.parse(newForm.attachments): [];
      this.form = newForm;
      if(this.form.customerName) this.custormerList = [{name: this.form.customerName, id: this.form.customerId, code: this.form.customerNo}];
      this.showForm = true;
      this.isHandle = false;
      this.isCheck = isCheck;
    },
    delFile(idx){
      this.form.attachments.splice(idx, 1)
    },
    async uploadFile(e) {
      var files = e.target.files;
      var $this = this;
      Object.keys(files).forEach(function(key){
        var file = files[key];
        if(file.size / 1024 / 1024 > 20) return $this.mobileAlert('上传单个文件大小不能超过20MB!请压缩文件')
        var formData = new FormData();
        formData.append("file", file);
        formData.append("name", 'file');
        let newfile = {
          name: file.name,
          url: '',
          size: file.size,
          uploader: $this.userInfo.realName,
          time: dateUtil.thisDay()
        }
        $this.form.attachments.push(newfile)
        $this.$httpN.upload('fileUpload', formData).then(res => {
          if(res.data.code === 0) {
            newfile.url = res.data.url;;
          }else if(res.data.code === 500) {
            $this.form.attachments.pop();
          }
        })
      })
      e.target.value = '';
    },
    selectDingUsers(target) {
      this.complexPicker(1, [], []).then(
        data => {
          target.assigneeId = data[0].emplId;
          target.assigneeName = data[0].name;
        }
      );
    },
    delMember(target) {
      target.assigneeId = '';
      target.assigneeName = '';
    },
    async saveForm() {
      this.custormerList.forEach((item) => {
        if(item.id === this.form.customerId) {
          this.form.customerName = item.name;
          this.form.customerNo = item.code;
        };
      })
      if(!formUtil.verifyData(this.form, this.formVerify)) return;
      if(!await this.$httpN.postB('crm/tdl/save', this.form)) return;
      formUtil.submitSuccess('成功');
      this.showForm = false;
      this.searchItem(true);
    },
    async remoteMethod(query) {
      if (query !== '' && query.length >= 2) {
        this.loading = true;
        this.custormerList = await this.$httpN.postQ('mpb/customer/getByName', {name: query});
        this.loading = false;
      } else {
        this.custormerList = [];
      }
    },
    sizeChangeHandle(limit) {
      this.pageSize = limit;
      this.searchItem(true);
    },
    currentChangeHandle(page) {
      this.page = page;
      this.searchItem();
    },
    async searchItem(init) {
      if(init) this.page = 1;
      let data = await this.$httpN.postB('crm/tdl/list',{
        priority: this.filterData.priority,
        taskType: this.filterData.taskType,
        assigneeId: this.filterPeople.assigneeId,
        customerNo: this.filterData.customerNo,
        processed: this.filterData.processed,
        page: this.page,
        limit: this.pageSize,
        asc: this.asc,
        sortField: this.sortFile
      })
      this.tableData = data.list;
      this.totalPage = data.totalCount
    }
  }
}
</script>

<style lang="scss" scoped>
  .header{
    position: relative;
    padding: 10px 0 0 20px ;
    .filter{
      cursor: pointer;
      float: right;
      margin-right: 30px;
      line-height: 30px;
      img{
        width: 16px;
        margin-right: 3px;
      }
    }
    .mask{
      position: fixed;
      height: 100vh;
      width: 100%;
      top: 0;
      right: 0;
      z-index: 3;
    }
    .filter-wrapper{
      position: absolute;
      width: 315px;
      padding-bottom: 20px;
      background: white;
      top: 48px;
      right: 20px;
      z-index: 99;
      border-radius: 5px;
      box-shadow: 0 0 3px black;
      .filter-header{
        line-height: 40px;
        padding-left: 16px;
        border-bottom: 1px solid #DDD;
        margin-bottom: 20px;
      }
      .filter-arrow{
        width:12px;
        height:12px;
        position: absolute;
        top: -7px;
        right: 20px;
        box-shadow: 0 0 3px black;
        transform: rotate(45deg);
      }
      .filter-white{
        width:18px;
        height:18px;
        position: absolute;
        top: -2px;
        right: 17px;
        border-radius: 3px;
        background: white;
      }
    }
  }
  .data-wrapper{
    padding: 0 20px;
    margin-top: 10px;
  }
  .select-btn{
    display: inline-block;
    font-weight: normal;
    margin-right: 5px;
    width: 80px;
    height: 28px;
    border-radius: 30px;
    background: #FAFAFA;
    border: 1px solid #ECECEC;
    position: relative;
    line-height: 28px;
    color: #7982A7;
    font-size: 12px;
    text-align: center;
    position: relative;
    cursor: pointer;
    .del{
      position: absolute;
      top:0;
      left: 0;
      width: 100%;
      height: 100%;
      border-radius: 30px;
      color: white;
      text-align: center;
      background:rgba(130, 130, 130, 0.9);
      display: none;
    }
    &:hover{
      .del{
        display: block;
      }
    }
  }
  .fileitem{
    cursor: pointer;
    line-height: 32px;
    margin-bottom: 5px;
    background: #F5F5F5;
    width: 474px;
    padding-left:15px;
    font-size: 12px;
    .uploadtip{
      float:right;
      margin-right: 20px;
      cursor: pointer;
    }
  }
  .addfilebtn{
    cursor: pointer;
    color: #909399;
    display: block;
    font-weight: normal;
  }
</style>